/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.edu.agh.administracja.networkconfig.model;

import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import pl.edu.agh.administracja.networkconfig.model.util.ShellExecutor;

/**
 *
 * @author radek
 */
public class PasswordHolder {

    private static String password;
    private static final int maxAttempts = 3;

    public static String getPassword() {
        int numAttempts = 0;
        while (numAttempts < maxAttempts && password == null) {
            JPasswordField passwordField = new JPasswordField();
            passwordField.setEchoChar('*');

            Object[] obj = {
                "Podaj hasło roota: (Próba " + (numAttempts + 1)
                + "/" + maxAttempts + ")\n\n",
                passwordField
            };

            Object stringArray[] = {"OK", "Anuluj"};

            if (JOptionPane.showOptionDialog(null, obj, "Potrza hasła",
                    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, stringArray, obj) == JOptionPane.YES_OPTION) {
                password = new String(passwordField.getPassword());
                verify();
                numAttempts++;
            } else {
                // gracefully break the loop
                numAttempts = maxAttempts;
            }

        }
        return password;
    }

    private static void verify() {

        String result = ShellExecutor.executeSynchronously("echo '" + password + "' | sudo -S ls > /dev/null 2>&1;echo $?");
        if (Integer.parseInt(result.trim()) != 0) {
            password = null;
        }
    }
}
